package net.sashag.nadlandroid;

import org.json.JSONException;

import com.googlecode.androidannotations.annotations.Background;
import com.googlecode.androidannotations.annotations.EReceiver;
import com.googlecode.androidannotations.annotations.SystemService;
import com.parse.ParseException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

@EReceiver
public class NewApartmentReceiver extends BroadcastReceiver {
	
	@SystemService protected NotificationManager notificationManager;
	
	private static int notificationId; //Increasing, while the application is alive this will ensure we get fresh notifications
	
	@Override
	public void onReceive(Context context, Intent intent) {
		NadlandroidPushNewApartment newApartment;
		try {
			newApartment = NadlandroidPushNewApartment.fromIntent(intent);
		} catch (JSONException e) {
			Log.w("NewApartmentReceiver", "Error parsing new apartment message: " + e.getMessage());
			return;
		}
		postNotification(newApartment, context);
	}
	
	@Background
	protected void postNotification(NadlandroidPushNewApartment newApartment, Context context) {
		Apartment apartment;
		try {
			apartment = Apartment.fromId(newApartment.getApartmentId());
		} catch (ParseException e) {
			Log.w("NewApartmentReceiver", "Error retrieving apartment information: " + e.getMessage());
			return;
		}
		Notification notification = new Notification(
				R.drawable.newapartmentnotification,
				"New apartment added in " + newApartment.getRegionName(),
				newApartment.getTime().getTime());
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		Intent activityLaunch = new ApartmentDetailsActivity_.IntentBuilder_(context).apartment(apartment).get();
		activityLaunch.setFlags(activityLaunch.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent contentIntent = PendingIntent.getActivity(context, -1, activityLaunch, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.setLatestEventInfo(context,
				"New Apartment in " + newApartment.getRegionName(),
				String.format("Price: %d, bedrooms: %d, address: %s",
						apartment.getPrice(), apartment.getBedrooms(), apartment.getAddress()),
				contentIntent);
		notificationManager.notify(++notificationId, notification);
	}

}
